package at.fhooe.tuxgestures.keysimulator;

import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;

public class KeyProcess implements Runnable {

	//the flag(running) is thread safe by using a volatile variable
	private volatile boolean running = true;
	private Robot robot;
	private int keyEvent; //it takes the state(int) which corresponds to a specific key button
	
	public KeyProcess(int state) {
		try {
			robot = new Robot();
		} catch (AWTException e) {
			e.printStackTrace();
		}
		keyEvent = state;
	}
	
	@Override
	public void run() {
		//robot.keyRelease(keyEvent);
		
		switch (keyEvent) {
		case 0:
			running = false;
			robot.keyPress(KeyEvent.VK_ESCAPE);
			robot.keyRelease(KeyEvent.VK_ESCAPE);
			robot.keyPress(KeyEvent.VK_ALT);
			try {
				Thread.sleep(2);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			robot.keyPress(KeyEvent.VK_TAB);
			try {
				Thread.sleep(2);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			robot.keyRelease(KeyEvent.VK_TAB);
			robot.keyRelease(KeyEvent.VK_ALT);
			break;
		case 1:
			running = false;
			robot.keyPress(KeyEvent.VK_ALT);
			try {
				Thread.sleep(2);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			robot.keyPress(KeyEvent.VK_TAB);
			try {
				Thread.sleep(2);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			robot.keyRelease(KeyEvent.VK_TAB);
			robot.keyRelease(KeyEvent.VK_ALT);
			try {
				Thread.sleep(2);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			robot.keyPress(KeyEvent.VK_ESCAPE);
			robot.keyRelease(KeyEvent.VK_ESCAPE);
			break;
		default:
			while (running) {
				robot.keyPress(keyEvent);
			}
			robot.keyRelease(keyEvent);
			//if (keyEvent != 0 && keyEvent != 1) {
				//robot.keyRelease(keyEvent);
			//}
			break;
		}
		
		/*while (running) {
			robot.keyPress(keyEvent);
		}
		if (keyEvent != 0 && keyEvent != 1) {
			robot.keyRelease(keyEvent);
		}*/
		
	}
	
	public void terminate() {
		if (keyEvent != 0 && keyEvent != 1) {
			robot.keyRelease(keyEvent);
	        running = false;
		}
    }

}
